﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;

namespace ElValWeb.ValidatorClientAdapters {
    class AndCompositeValidatorClientAdapter : BaseClientAdapter<AndCompositeValidatorData> {

        public AndCompositeValidatorClientAdapter(AndCompositeValidatorData validatorData)
            : base(validatorData) {
        }

        public override IEnumerable<ModelClientValidationRule> GetClientRules(Type ownerType) {
            var resultedMadelClient = new ModelClientValidationRule {
                ErrorMessage = ValidatorData.GetMessageTemplate(),
                ValidationType = "andComposite"
            };
            var anyOfInnerIsEmpty = false;

            var rulesOverall = new List<IEnumerable<ModelClientValidationRule>>();


            foreach (var validatorData in ValidatorData.Validators) {
                var rules = ClientAdapterFactory.GetAdapter(validatorData).GetClientRules(ownerType);
                anyOfInnerIsEmpty = (anyOfInnerIsEmpty || (rules.Count() == 0));
                rulesOverall.Add(rules);
            }

            if (anyOfInnerIsEmpty) {
                return new ModelClientValidationRule[] { };
            }

            resultedMadelClient.ValidationParameters["innerValidators"] = rulesOverall;

            return new[] { resultedMadelClient };
        }
    }
}